import { safetyCheck, verifyCode, login, info, logout } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

const state = {
  info: {},
  user: {},
  vcToken: '',
  token: '',
  accessRoutes: []
}

const mutations = {
  SET_INFO: (state, data) => {
    state.info = data
  },
  SET_USER: (state, data) => {
    state.user = data
    // 用户信息不存在
    if (!data) {
      // 删除Token
      removeToken()
    }
  },
  SET_VC_TOKEN: (state, vcToken) => {
    state.vcToken = vcToken
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  RESET_TOKEN: state => {
    state.token = ''
    removeToken()
  },
  SET_ACCESS_ROUTES: (state, accessRoutes) => {
    state.accessRoutes = accessRoutes
  }
}

const actions = {
  // safetyCheck
  safetyCheck({ commit, state }) {
    return new Promise((resolve, reject) => {
      safetyCheck()
        .then(data => {
          resolve(data)
          commit('SET_VC_TOKEN', data.vcToken)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // verifyCode
  verifyCode({ state }) {
    return new Promise((resolve, reject) => {
      const vcToken = state.vcToken
      verifyCode(vcToken)
        .then(data => {
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // login
  login({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      const vcToken = state.vcToken
      const lrTime = new Date().getTime()
      login({ vcToken, lrTime }, data)
        .then(data => {
          commit('SET_TOKEN', data.token)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // info
  info({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      info({ }).then(data => {
        commit('SET_INFO', data)
        commit('SET_USER', data.user)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      var headers = {}
      logout(headers)
        .then(data => {
          commit('RESET_TOKEN')
          commit('SET_INFO', {})
          commit('SET_USER', {})
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // resetToken
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('RESET_TOKEN')
      commit('SET_INFO', {})
      commit('SET_USER', {})
      resolve()
    })
  },
  accessRoutes({ commit }, accessRoutes) {
    commit('SET_ACCESS_ROUTES', accessRoutes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
